package com.korion.srceencapture;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.util.Log;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenyinying
 * @date 2020/9/27
 */
public class SurfaceControlProxy {
    private static final String CLASS_NAME = "android.view.SurfaceControl";
    private static final String TAG = "SurfaceControlProxy";
    private static Class realClass;

    private static Map<String, Method> sMethodCaches = new HashMap<>();

    static {
        try {
            realClass = Class.forName(CLASS_NAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Bitmap screenshot(int width, int height) {
        if (isValid()){
            String name = "screenshot";
            Method method = sMethodCaches.get(sign(name, Integer.class, Integer.class));
            if (method == null) {
                try {
                    method = realClass.getDeclaredMethod(name, int.class, int.class);
                    sMethodCaches.put(sign(name, int.class, int.class), method);
                } catch (NoSuchMethodException e) {
                    Log.e(TAG, "can't reflect "+name+" method.");
                }
            }
            Bitmap result = null;
            if (method != null) {
                try {
                    Log.d(TAG, "invoke "+method.getName());
                    result = (Bitmap) method.invoke(null, width, height);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
        return null;
    }

    public static String sign(String methodName, Class... params){
        StringBuilder sb = new StringBuilder(methodName);
        for (Class obj: params){
            String name = obj.getSimpleName();
            sb.append('_').append(name);
        }
        return sb.toString();
    }

    public static boolean isValid(){
        return realClass != null;
    }


    public static void main(String[] argv){
//        System.out.println("Hello world");
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        System.out.println("metrics:("+metrics.widthPixels+", "+metrics.heightPixels+")");
        Bitmap bitmap = SurfaceControlProxy.screenshot(metrics.widthPixels, metrics.heightPixels);
        String name = System.currentTimeMillis()+".jpg";
        System.out.println("name:"+name);
        BitmapHandler.saveBitmapToFile(bitmap, "/sdcard/Android/"+name);
    }

}
